package com.catalina.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Servlet Filter implementation class SystemInterceptor
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	/**
	 * @see HandlerInterceptor#preHandle(HttpServletRequest,
	 *      HttpServletResponse, Object)
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
			throws java.lang.Exception {
		Object obj = request.getSession().getAttribute("user");
		if (obj == null) {
			String header = request.getHeader("X-Requested-With");// 得到请求头信息
			if (header != null && header.equals("XMLHttpRequest")) {
				//response.getWriter().write("/login");
				return true;
			} else {
				//response.sendRedirect("/login");
				request.getRequestDispatcher("/login").forward(request, response);
				return false;
			}
		}
		return true;
	}

	/**
	 * @see HandlerInterceptor#postHandle(HttpServletRequest,
	 *      HttpServletResponse, Object, ModelAndView)
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
			ModelAndView modelAndView) throws java.lang.Exception {
	}

	/**
	 * @see HandlerInterceptor#afterCompletion(HttpServletRequest,
	 *      HttpServletResponse, Object, Exception)
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2,
			Exception exception) throws java.lang.Exception {

	}
}
